﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using G.Navigate;
using G.WeiBo.WebAPI.Domain;
using G.WeiBo.View.ChildWindows;
using Microsoft.Phone.Tasks;
using G.Controls;
using G.WeiBo.WebAPI.Response;
using G.WeiBo.WebAPI.Request;
using System.Windows.Controls.Primitives;

namespace G.WeiBo.View
{
    public partial class UserInfoPage : GBasePage
    {
        public UserInfoPage()
        {
            InitializeComponent();
            //this.NavigationCacheMode
        }

        UserInfo userInfo;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            userInfo = this.NavigationContext.Param as UserInfo;
            if (userInfo != null)
            {
                SetUserInfo();
            }
            else
            {
                string username = this.NavigationContext.QueryString["username"];
                GlobalStaticData.Client.Execute(new GetUserInfoRequest { NickName = username }, (c) =>
                {
                    if (!c.IsError)
                    {
                        this.userInfo = c.Response;
                        SetUserInfo();
                    }
                });
            }

        }

        private void SetUserInfo()
        {
            pivot.Title = userInfo.NickName;
            WebClient client = new WebClient();
            //client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            //client.OpenReadAsync(new Uri(userInfo.MaxHeadImag, UriKind.Absolute));
            txtUrl.Inlines.Clear();
            txtUrl.Inlines.Add(new Run { Text = "博客:", Foreground = new SolidColorBrush(Colors.Red) });
            txtUrl.Inlines.Add(new Run { Text = userInfo.Url, TextDecorations = TextDecorations.Underline });
            gridUserInfo.DataContext = userInfo;
            GlobalStaticData.Client.Execute(new ExistsAttenRequest { TargetId = userInfo.Id }, (c) =>
            {
                if (!c.IsError)
                {
                    this.SetAtten(c.Source.Following);
                }
            });
        }
        private void SetAtten(bool? isAtten)
        {

            Microsoft.Phone.Shell.ApplicationBarIconButton btn = this.ApplicationBar.Buttons[1] as Microsoft.Phone.Shell.ApplicationBarIconButton;
            if (isAtten == true)
            {
                stackPanel_Atten.Visibility = System.Windows.Visibility.Visible;
                btn.IconUri = new Uri("/icons/appbar.minus.rest.png", UriKind.Relative);
                btn.Text = "取消关注";
                btn.IsEnabled = true;
            }
            else if (isAtten == false)
            {
                btn.Text = "添加关注";
                btn.IconUri = new Uri("/icons/appbar.new.rest.png", UriKind.Relative);
                btn.IsEnabled = true;
                stackPanel_Atten.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                btn.IsEnabled = false;
            }


        }

        System.IO.Stream stream;
        //void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        //{
        //    if (e.Error == null)
        //    {
        //        stream = e.Result;
        //        System.Windows.Media.Imaging.BitmapImage source = new System.Windows.Media.Imaging.BitmapImage();
        //        try
        //        {
        //            source.SetSource(stream);
        //            this.img.Source = source;
        //        }
        //        catch { }

        //    }
        //    loadingIndicator_headImage.StopAnimation();
        //}

        private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Image img = sender as Image;
            BrowserBigImageChildWindow childWindow = new BrowserBigImageChildWindow();
            childWindow.IsOpen = true;
            childWindow.Url = new Uri(img.Tag as string, UriKind.RelativeOrAbsolute);
            e.Handled = true;
        }

        private void txtUrl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            WebBrowserTask task = new WebBrowserTask();
            task.Uri = new Uri(userInfo.Url, UriKind.Absolute);
            task.Show();
        }

        //private void Image_ImageOpened(object sender, RoutedEventArgs e)
        //{
        //    loadingIndicator_headImage.StopAnimation();
        //}

        private void btnAddAtten_Click(object sender, EventArgs e)
        {
            if (userInfo == null)
            {
                this.ShowState("请在加载玩数据后执行本操作");
                return;
            }
            Microsoft.Phone.Shell.ApplicationBarIconButton btn = this.ApplicationBar.Buttons[1] as Microsoft.Phone.Shell.ApplicationBarIconButton;
            btn.IsEnabled = false;
            if (stackPanel_Atten.Visibility == System.Windows.Visibility.Visible)
            {
                if (MessageBox.Show("确定要取消对" + userInfo.NickName + "的关注？", "确认", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    GlobalStaticData.Client.Execute(new DeleteAttenRequest { UserId = userInfo.Id, }, (c) =>
                    {
                        if (!c.IsError)
                        {
                            this.SetAtten(false);
                            this.ShowState("已经取消对" + userInfo.NickName + "的关注");
                        }

                    });
                }
            }
            else
            {

                GlobalStaticData.Client.Execute(new AddAttenRequest { UserId = userInfo.Id, }, (c) =>
                {
                    if (!c.IsError)
                    {
                        this.SetAtten(true);
                        this.ShowState("关注成功！");
                    }
                });

            }
        }


        private void listBoxtUserMessage_BeginLoadData(object sender, PageEventArgs e)
        {
            GlobalStaticData.Client.Execute(new GetUserTimelineRequest { UserID = userInfo.Id, Page = e.PageNum, Count = e.PageSize }, (c) =>
            {
                if (c.Messages == null || c.Messages.Count() < 1)
                {
                    listBoxtUserMessage.CancelPageListBox();
                }
                listBoxtUserMessage.LoadData<Message>(c.Messages);
            });
        }



        private void listBoxtFriends_BeginLoadData(object sender, PageEventArgs e)
        {
            int pageNum = -1;
            object nextPage = this.ReadFromState("listBoxtFriendsNextPage");
            if (nextPage != null)
                pageNum = (int)nextPage;
            if (pageNum == 0)
            {
                listBoxtFriends.CancelPageListBox();
                return;
            }


            GlobalStaticData.Client.Execute(new GetFriendsRequest { UserId = userInfo.Id, Page = pageNum, Count = e.PageSize }, (c) =>
            {
                this.SaveToState("listBoxtFriendsNextPage", c.NextPage);
                listBoxtFriends.LoadData<UserInfo>(c.Users);
                if (c.Users == null || c.Users.Count() < 1)
                {
                    listBoxtFriends.CancelPageListBox();
                }
            });

        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GetDatas();
        }
        private void GetDatas()
        {
            if (pivot.SelectedIndex == 1 && listBoxtUserMessage.ItemsSource == null)
            {
                listBoxtUserMessage.EnableTombstoneListBox<Message>(this);
            }
            else if (pivot.SelectedIndex == 2 && listBoxtFriends.ItemsSource == null)
            {
                this.listBoxtFriends.EnableTombstoneListBox<UserInfo>(this);
            }
            else if (pivot.SelectedIndex == 3 && listBoxtFans.ItemsSource == null)
            {
                this.listBoxtFans.EnableTombstoneListBox<UserInfo>(this);
            }
        }
        private void listBoxtFans_BeginLoadData(object sender, PageEventArgs e)
        {
            int pageNum = -1;
            object nextPage = this.ReadFromState("listBoxtFansNextPage");
            if (nextPage != null)
                pageNum = (int)nextPage;
            if (pageNum == 0)
            {
                listBoxtFans.CancelPageListBox();
                return;
            }

            GlobalStaticData.Client.Execute(new GetFansRequest { UserId = userInfo.Id, Page = pageNum, Count = e.PageSize }, (c) =>
            {
                this.SaveToState("listBoxtFansNextPage", c.NextPage);
                listBoxtFans.LoadData<UserInfo>(c.Users);
                if (c.Users == null || c.Users.Count() < 1)
                {
                    listBoxtFans.CancelPageListBox();
                }
            });
        }

        private void TextButton_Click(object sender, RoutedEventArgs e)
        {
            ButtonBase btn = sender as ButtonBase;
            this.pivot.SelectedIndex = int.Parse(btn.Tag as string);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {

            Refresh();
        }
        private void Refresh()
        {
            if (pivot.SelectedIndex == 1)
            {
                listBoxtUserMessage.ClearItems();
            }
            else if (pivot.SelectedIndex == 2)
            {
                this.SaveToState("listBoxtFriendsNextPage", -1);
                this.listBoxtFriends.ClearItems();
            }
            else if (pivot.SelectedIndex == 3)
            {
                this.SaveToState("listBoxtFansNextPage", -1);
                this.listBoxtFans.ClearItems();
            }
            GetDatas();
        }
    }
}